

#include "IO.h"
#include "BSP_SPI.h"
#include "BSP_Config.h"

static const IO_T RFIO_RST = IO_INIT_TABLE(GPIOB, GPIO_PIN_3);
static const IO_T RFIO_IRQ = IO_INIT_TABLE(GPIOB, GPIO_PIN_4);

#define SPI_NSS_LOW()	do{ BSP_SPI_SetNSS(RFIO_SpiId,0); }while(0)
#define SPI_NSS_HIGH()	do { BSP_SPI_SetNSS(RFIO_SpiId,1); }while(0)

static void RFIO_GPIO_Init(void){
	IO_Init(&RFIO_RST, IO_Mode_OUT);
	IO_Set(&RFIO_RST, 0);

//		IO_Init(&RFIO_IRQ, IO_Mode_IN);
}


void RFIO_Init(void){
	BSP_SPI_Init(RFIO_SpiId, 4000000);//RFID
	RFIO_GPIO_Init();
}

uint8_t RFIO_SPI_Exchange(uint8_t TxByte)
{
	return BSP_SPI_Exchange(RFIO_SpiId,TxByte);
}

void RFIO_SPI_SetNSS(uint8_t state){
	BSP_SPI_SetNSS(RFIO_SpiId, state);
}

void RFIO_SetReset(uint8_t state){
	IO_Set(&RFIO_RST, state);
}

uint8_t RFIO_Read(uint8_t addr){
	uint8_t val;
	
	SPI_NSS_LOW();
	RFIO_SPI_Exchange(addr); 
	val = RFIO_SPI_Exchange(0);	
	SPI_NSS_HIGH();
	return val;
}

void RFIO_Write(uint8_t addr, uint8_t val){
	SPI_NSS_LOW();
	RFIO_SPI_Exchange(addr); 
	RFIO_SPI_Exchange(val);
	SPI_NSS_HIGH();
}

void RFIO_ReadSequence(uint8_t addr, uint8_t * buf, uint16_t len){
	unsigned char i, ucAddr, AddrRShift,rlen;

	if ( len <= 64 )
		rlen = len ; // Plus the 
	else
		rlen = 64 ;

	SPI_NSS_LOW();
	AddrRShift = (addr << 1) & 0x7E;
  	ucAddr = AddrRShift | 0x80; 	//read mode
	
	RFIO_SPI_Exchange(ucAddr);
	if(rlen == len)
	{
		for(i = 0; i < (rlen - 1); i++){
			buf[i] = RFIO_SPI_Exchange(AddrRShift);
		}
		buf[i] = RFIO_SPI_Exchange(0);	
	}
	else
	{
		for(i = 0; i < rlen ; i++)
			buf[i] = RFIO_SPI_Exchange(addr);	
	}

	SPI_NSS_HIGH();
}

void RFIO_WriteSequence(uint8_t addr, uint8_t * buf, uint16_t len){
	unsigned char i, ucAddr, wlen;

	if( len <= 64 )
		wlen = len ; // Plus the 
	else
		wlen = 64 ;

	SPI_NSS_LOW();
	ucAddr =((addr << 1) & 0x7E);	

	RFIO_SPI_Exchange(ucAddr);
	for(i = 0; i < wlen; i++)
		RFIO_SPI_Exchange(buf[i]);
	
	SPI_NSS_HIGH();
}

int RFIO_Irq(void){
	return IO_Get(&RFIO_IRQ);
}



